﻿import 'dart:async';

import 'package:flutter/material.dart';
import 'package:myapp/page/address/address.dart';
import 'package:myapp/page/bluetooth/index.dart';
import 'package:myapp/state/bluetooth.dart';
import 'package:myapp/state/notifications.dart';
import 'package:provider/provider.dart';
import 'package:myapp/page/webview/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  // WidgetsFlutterBinding.ensureInitialized();
  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (_) => BluetoothStore()),
      ChangeNotifierProvider(create: (_) => NotificationsStore()),
    ],
    child: const App(),
  ));
}

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          platform: TargetPlatform.iOS,
          colorScheme: ColorScheme.fromSeed(
              seedColor: const Color.fromARGB(255, 204, 175, 255)),
          useMaterial3: true,
        ),
        home: const MyApp(),
    );
  }

}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() {
    return _App();
  }
}

class _App extends State<MyApp> {

  Future<Map<String, String>> _getAddress() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String ip = prefs.getString('ip') ?? '';
    String port = prefs.getString('port') ?? '';

    return {'ip': ip, 'port': port};
  }

  @override
  void initState() {
    super.initState();
    context.read<NotificationsStore>().init();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initBluetooth();
    });
  }

  _initBluetooth() async {
    try {
      await context.read<BluetoothStore>().autoConnect();
    } catch(e) {
      showAlert();
    }
  }

  void showAlert() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('提示', style: TextStyle(fontSize: 20)),
          content: const Text('检测到当前设备没有连接蓝牙，是否前往配置蓝牙页面！'),
          actions: [
            TextButton(
              child: const Text('前往设置'),
              onPressed: () {
                Navigator.of(context).pop();
                Navigator.push(context, MaterialPageRoute(builder: (context) => const Bluetooth()));
              },
            ),
            TextButton(
              child: const Text('稍后设置'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _getAddress(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          // 显示加载状态
          return _loadingView();
        } else if (snapshot.hasError) {
          // 处理错误
          return const Text('Error loading data');
        } else {
          // 数据加载完成
          final Map<String, String> data = snapshot.data!;
          final ip = data['ip']!;
          final port = data['port']!;
          return ip.isNotEmpty && port.isNotEmpty
            ? MyView(ip: ip, port: port)
            : const Address();
        }
      });
  }

  Widget _loadingView(){
    return Container(
      width: double.infinity,
      color: Colors.white,
      child: Center(
        child: Image.asset(
          'assets/images/lod.gif',
          width: 100,
          height: 100,
        )
      )
    );
  }
}
